package c6;
import java.util.Comparator;
import java.util.IntSummaryStatistics;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 归约和汇总
 */
public class Reducing {
    public static void main(String[] args) {
        long howManyDishes=Dish.menu.stream().collect(Collectors.counting());
        long howManyDishes2=Dish.menu.stream().count();
        long howManyDishes3= (long) Dish.menu.size();
        System.out.println("dishes count: "+howManyDishes);

        Comparator<Dish> dishComparator=Comparator.comparing(Dish::getCalories);
        Optional<Dish> maxDish=Dish.menu.stream().collect(Collectors.maxBy(dishComparator));
        Optional<Dish> minDish=Dish.menu.stream().collect(Collectors.minBy(dishComparator));
        System.out.println("maxDish:"+maxDish.get());
        System.out.println("minDish:"+minDish.get());

        //数据统计
        int totalCalories=Dish.menu.stream().collect(Collectors.summingInt(Dish::getCalories));
        double avgCalories=Dish.menu.stream().collect(Collectors.averagingDouble(Dish::getCalories));
        IntSummaryStatistics intSummaryStatistics=Dish.menu.stream().collect(Collectors.summarizingInt(Dish::getCalories));
        System.out.println("total: "+totalCalories);
        System.out.println("avg: "+avgCalories);
        System.out.println("statistics: "+intSummaryStatistics.toString());

        //join
        String shortMenu=Dish.menu.stream().map(Dish::getName).collect(Collectors.joining(","));
        System.out.println("joining: "+shortMenu);

        //reduce归约写法
        int totalCalories2=Dish.menu.stream().collect(Collectors.reducing(0,Dish::getCalories,(d1,d2)->d1+d2));
        Optional<Dish> maxCaloriesDish=Dish.menu.stream().collect(Collectors.reducing((d1,d2)->d1.getCalories()>d2.getCalories()?d1:d2));
        System.out.println("total2: "+totalCalories2);
        System.out.println("maxCalories dish: "+maxCaloriesDish.get());

        int totalCalories3 = Dish.menu.stream().mapToInt(Dish::getCalories).sum();
        System.out.println("最简写法得到total："+totalCalories3);
    }
}
